package cn.vconinfo.lims.delivery.service;

import cn.vconinfo.database.annotation.TargetDataSource;
import cn.vconinfo.lims.delivery.entity.SpecimenCheckAndProjectDocumentIdsDTO;
import cn.vconinfo.lims.delivery.entity.TableResponseDTO;
import cn.vconinfo.lims.delivery.entity.TestSubItemQuery;
import cn.vconinfo.lims.delivery.entity.WLisRequestQuery;
import cn.vconinfo.lims.delivery.mapper.CustomConfigMapper;
import cn.vconinfo.lims.delivery.mapper.HospitalProjectLinkMapper;
import cn.vconinfo.lims.delivery.mapper.WLisRequestInfoMapper;
import cn.vconinfo.lims.delivery.mapper.WTestitemRelateMapper;
import cn.vconinfo.lims.delivery.model.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class RequestTestItemService {
    private final HospitalProjectLinkMapper wRequestitemRelateMapper;
    private final WTestitemRelateMapper wTestitemRelateMapper;
    private final WLisRequestInfoMapper wLisRequestInfoMapper;
    private final InspectAppService inspectAppService;

    private final CustomConfigMapper customConfigMapper;

    /**
     *  根据条件获取开单项目
     *
     * @param relate
     * @return
     */
    @TargetDataSource("master")
    public List<HospitalProjectLink> queryRequestItemRelate(HospitalProjectLink relate){
        HospitalProjectLinkExample example = new HospitalProjectLinkExample();
        HospitalProjectLinkExample.Criteria criteria = example.createCriteria();
        criteria.andObjectIdEqualTo(relate.getObjectId());

        if(StringUtils.isNotBlank(relate.getHospitalDocumentId())){
            criteria.andHospitalDocumentIdEqualTo(relate.getHospitalDocumentId());
        }
        List<HospitalProjectLink> relateList = wRequestitemRelateMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(relateList)){
            relateList = Collections.emptyList();
        }

        return relateList;
    }

    @TargetDataSource("master")
    public void insertRequestItemBatch(List<HospitalProjectLink> relateList){
        int handlerCnt = customConfigMapper.insertRequestItemRelateBatch(relateList);
        if(handlerCnt < 1){
            log.error("批量插入开单项目出错：{}", relateList);
        }
    }

    /**
     *  根据条件获取实验项目
     *
     * @param relate
     * @return
     */
    @TargetDataSource("master")
    public List<WTestitemRelate> querySubTestItemRelate(TestSubItemQuery relate){
        WTestitemRelateExample example = new WTestitemRelateExample();
        WTestitemRelateExample.Criteria criteria = example.createCriteria();
        criteria.andHospitalIdEqualTo(cn.vconinfo.base.utils.StringUtils.stringToLong(relate.getHospitalId()));

        if(StringUtils.isNotBlank(relate.getSubItemCode())){
            criteria.andSubItemCodeEqualTo(relate.getSubItemCode());
        }
        if(!CollectionUtils.isEmpty(relate.getProjectIdList())){
            criteria.andProjectIdIn(relate.getProjectIdList());
        }
        List<WTestitemRelate> relateList = wTestitemRelateMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(relateList)){
            relateList = Collections.emptyList();
        }

        return relateList;
    }

    /**
     *  获取检验子项目的对照关系
     *
     * @param relate
     * @return
     */
    @TargetDataSource("master")
    public Map<Long, WTestitemRelate> getTestSubItemMapping(TestSubItemQuery relate){
        List<WTestitemRelate> relateList = querySubTestItemRelate(relate);
        Map<Long, WTestitemRelate> subItemMap = relateList.parallelStream().collect(Collectors.toMap(WTestitemRelate::getProjectId, a->a, (k1, k2) -> k1));

        return subItemMap;
    }

    @TargetDataSource("master")
    public void insertSubTestItemBatch(List<WTestitemRelate> relateList){
        int handlerCnt = customConfigMapper.insertTestItemRelateBatch(relateList);
        if(handlerCnt < 1){
            log.error("批量插入实验项目出错：{}", relateList);
        }
    }

    /**
     *  根据条件获取申请单数据
     *
     * @param info
     * @return
     */
    @TargetDataSource("master")
    public List<WLisRequestInfo> queryLisRequestInfo(WLisRequestQuery info){
        WLisRequestInfoExample example = new WLisRequestInfoExample();
        WLisRequestInfoExample.Criteria criteria = example.createCriteria();
        criteria.andHospitalIdEqualTo(info.getHospitalId());
        if(StringUtils.isNotBlank(info.getBarCode())){
            criteria.andBarCodeEqualTo(info.getBarCode());
        }
        if(StringUtils.isNotBlank(info.getSampleNo())){
            criteria.andSampleNoEqualTo(info.getSampleNo());
        }
        if(info.getPatientId() != null){
            criteria.andPatientIdEqualTo(info.getPatientId());
        }
        if(info.getSamplingDateStart() != null){
            criteria.andSamplingDateGreaterThanOrEqualTo(info.getSamplingDateStart());
        }
        if(info.getSamplingDateEnd() != null){
            criteria.andSamplingDateLessThanOrEqualTo(info.getSamplingDateEnd());
        }
        if(info.getTransFlag() != null){
            criteria.andTransFlagEqualTo(info.getTransFlag());
        }

        List<WLisRequestInfo> requestInfoList = wLisRequestInfoMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(requestInfoList)){
            requestInfoList = Collections.emptyList();
        }

        return requestInfoList;
    }

    @TargetDataSource("master")
    public boolean updateLisRequestInfo(WLisRequestQuery info){
        WLisRequestInfoExample example = new WLisRequestInfoExample();
        WLisRequestInfoExample.Criteria criteria = example.createCriteria();
        criteria.andHospitalIdEqualTo(info.getHospitalId());
        criteria.andBarCodeEqualTo(info.getBarCode());

        WLisRequestInfo requestInfo = new WLisRequestInfo();
        requestInfo.setTransFlag(1);
        int handlerCnt = wLisRequestInfoMapper.updateByExampleSelective(requestInfo, example);
        return handlerCnt>0?true:false;
    }

    /**
     *  申请单记录表
     * @param requestInfo
     */
    @TargetDataSource("master")
    public void insertLisRequestInfo(WLisRequestInfo requestInfo, SpecimenCheckAndProjectDocumentIdsDTO projectDocumentIdsDTO){
        try{
            TableResponseDTO responseDTO = addRequestAndAddProjectDocuments(projectDocumentIdsDTO);
            if(responseDTO != null && responseDTO.getResponseCode().intValue() == 1){
                Assert.isTrue(wLisRequestInfoMapper.insertSelective(requestInfo) > 0, "插入申请记录失败");
            }
        }catch (Exception ex){
            log.error("插入申请记录出错", ex);
        }
    }

    @TargetDataSource("master")
    public TableResponseDTO addRequestAndAddProjectDocuments(SpecimenCheckAndProjectDocumentIdsDTO projectDocumentIdsDTO){
        TableResponseDTO responseDTO = null;
        try{
            responseDTO = inspectAppService.addRequestAndAddProjectDocuments(projectDocumentIdsDTO);
            log.info("申请单插入：{}", responseDTO);
        }catch (Exception ex){
            log.error("申请单插入出错：", ex);
            responseDTO = null;
        }

        return responseDTO;
    }

}
